{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "033341e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import datetime\n",
    "import time\n",
    "from datetime import date\n",
    "import pandas_ta as ta\n",
    "import matplotlib.pyplot as plt\n",
    "import plotly.graph_objects as go\n",
    "from plotly.subplots import make_subplots\n",
    "from yahoo_fin import stock_info as si\n",
    "import datetime\n",
    "import yfinance as yf\n",
    "from random import randint\n",
    "from time import sleep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "9d6f3276",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_historic_data(symbol, start_date_str, today_date_str, period, interval, prepost):\n",
    "    try:\n",
    "        df = yf.download(symbol, start=start_date_str, end=today_date_str, period=period, interval=interval, prepost=prepost)\n",
    "        #  Add symbol\n",
    "        df[\"Symbol\"] = symbol\n",
    "        return df\n",
    "    except:\n",
    "        print('Error loading stock data for ' + symbols)\n",
    "        return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "7627e070",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading data for BTC-USD\n",
      "[*********************100%***********************]  1 of 1 completed\n",
      "Loading data for ETH-USD\n",
      "[*********************100%***********************]  1 of 1 completed\n",
      "Loading data for BCH-USD\n",
      "[*********************100%***********************]  1 of 1 completed\n",
      "Loading data for LTC-USD\n",
      "[*********************100%***********************]  1 of 1 completed\n",
      "Loading data for BNB-USD\n",
      "[*********************100%***********************]  1 of 1 completed\n"
     ]
    },
    {
     "ename": "PermissionError",
     "evalue": "[Errno 13] Permission denied: 'C:\\\\dev\\\\trading\\\\tradesystem1\\\\data\\\\crypto\\\\2022-04-28_BNB-USD_1d_1m.csv'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mPermissionError\u001b[0m                           Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_12448/643487205.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     21\u001b[0m     \u001b[1;31m#  Save df\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     22\u001b[0m     \u001b[0mfile_name\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34mf\"{today_date_str}_{symbol}_{period}_{interval}.csv\"\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 23\u001b[1;33m     \u001b[0mdf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mto_csv\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf\"C:\\\\dev\\\\trading\\\\tradesystem1\\\\data\\\\crypto\\\\{file_name}\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     24\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     25\u001b[0m     \u001b[1;31m#  Avoid DOS issues\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\anaconda3\\envs\\tradesystem1\\lib\\site-packages\\pandas\\core\\generic.py\u001b[0m in \u001b[0;36mto_csv\u001b[1;34m(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, line_terminator, chunksize, date_format, doublequote, escapechar, decimal, errors, storage_options)\u001b[0m\n\u001b[0;32m   3561\u001b[0m         )\n\u001b[0;32m   3562\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 3563\u001b[1;33m         return DataFrameRenderer(formatter).to_csv(\n\u001b[0m\u001b[0;32m   3564\u001b[0m             \u001b[0mpath_or_buf\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   3565\u001b[0m             \u001b[0mline_terminator\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mline_terminator\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\anaconda3\\envs\\tradesystem1\\lib\\site-packages\\pandas\\io\\formats\\format.py\u001b[0m in \u001b[0;36mto_csv\u001b[1;34m(self, path_or_buf, encoding, sep, columns, index_label, mode, compression, quoting, quotechar, line_terminator, chunksize, date_format, doublequote, escapechar, errors, storage_options)\u001b[0m\n\u001b[0;32m   1178\u001b[0m             \u001b[0mformatter\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfmt\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   1179\u001b[0m         )\n\u001b[1;32m-> 1180\u001b[1;33m         \u001b[0mcsv_formatter\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msave\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m   1181\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   1182\u001b[0m         \u001b[1;32mif\u001b[0m \u001b[0mcreated_buffer\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\anaconda3\\envs\\tradesystem1\\lib\\site-packages\\pandas\\io\\formats\\csvs.py\u001b[0m in \u001b[0;36msave\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m    239\u001b[0m         \"\"\"\n\u001b[0;32m    240\u001b[0m         \u001b[1;31m# apply compression and byte/text conversion\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 241\u001b[1;33m         with get_handle(\n\u001b[0m\u001b[0;32m    242\u001b[0m             \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfilepath_or_buffer\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    243\u001b[0m             \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmode\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\anaconda3\\envs\\tradesystem1\\lib\\site-packages\\pandas\\io\\common.py\u001b[0m in \u001b[0;36mget_handle\u001b[1;34m(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)\u001b[0m\n\u001b[0;32m    787\u001b[0m         \u001b[1;32mif\u001b[0m \u001b[0mioargs\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mencoding\u001b[0m \u001b[1;32mand\u001b[0m \u001b[1;34m\"b\"\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mioargs\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmode\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    788\u001b[0m             \u001b[1;31m# Encoding\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 789\u001b[1;33m             handle = open(\n\u001b[0m\u001b[0;32m    790\u001b[0m                 \u001b[0mhandle\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    791\u001b[0m                 \u001b[0mioargs\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmode\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mPermissionError\u001b[0m: [Errno 13] Permission denied: 'C:\\\\dev\\\\trading\\\\tradesystem1\\\\data\\\\crypto\\\\2022-04-28_BNB-USD_1d_1m.csv'"
     ]
    }
   ],
   "source": [
    "# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max\n",
    "# fetch data by interval (including intraday if period < 60 days)\n",
    "        # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo\n",
    "period = '1d'\n",
    "TE: 7 days is the max allowed\n",
    "days = datetime.timedelta(7)\n",
    "start_date = today - days\n",
    "start_date_str = datetime.datetime.strftime(start_date, \"%Y-%m-%d\")\n",
    "\n",
    "#  Fetch data for coin symbols\n",
    "symbols = ['BTC-USD','ETH-USD','BCH-USD','LTC-USD','BNB-USD','BAT-USD',\n",
    "           'XLM-USD','DOGE-USD','DOGE-USD','COMP-USD','ALGO-USD','OMG-USD']\n",
    "for symbol in symbols:\n",
    "    print(f\"Loading data for {symbol}\")\n",
    "    df = load_historic_data(symbol, start_date_str, today_date_str, period, interval, prepost)\n",
    "    #  Save df\n",
    "    file_name = f\"{today_date_str}_{symbol}_{period}_{interval}.csv\"\n",
    "    df.to_csv(f\"C:\\\\dev\\\\trading\\\\tradesystem1\\\\data\\\\crypto\\\\{file_name}\")\n",
    "    \n",
    "    #  Avoid DOS issues\n",
    "    sleep(randint(0,3))interval = '1m'\n",
    "prepost = True\n",
    "today = datetime.date.today()\n",
    "today_date_str = today.strftime(\"%Y-%m-%d\")\n",
    "\n",
    "#  NO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2bacca3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_graph(df):\n",
    "    fig = make_subplots(rows=1, cols=1)\n",
    "\n",
    "    #  Plot close price\n",
    "    fig.add_trace(go.Line(x = df.index, y = df['Close'], line=dict(color=\"blue\", width=1), name=\"Close\"), row = 1, col = 1)\n",
    "    \n",
    "    fig.update_layout(\n",
    "        title={'text':'7 days, 1m interval', 'x':0.5},\n",
    "        autosize=False,\n",
    "        width=800,height=400)\n",
    "    fig.update_yaxes(range=[0,1000000000],secondary_y=True)\n",
    "    fig.update_yaxes(visible=False, secondary_y=True)  #hide range slider\n",
    "    \n",
    "    fig.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "213ef3fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = load_historic_data('BTC-USD', start_date_str, today_date_str, period, interval, prepost)\n",
    "plot_graph(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7f992e7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:tradesystem1]",
   "language": "python",
   "name": "conda-env-tradesystem1-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
